﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace Sern.Test
{
    public static class ComponentLocatorTestHelper
    {
        public static Regex CallingTypeRegex = new Regex(@"^(?<TypeName>[a-zA-Z](\w|_|\.)*?)\+");

        public static void RegisterTestInstance<T>(this IUnityContainer container, T instance, string name = "")
        {
            var testRegistrationName = GetTestRegistrationName(name);

            container.RegisterInstance(testRegistrationName, instance);
        }

        public static void RegisterTestType<T,U>(this IUnityContainer container, string name = "")
            where U : T
        {
            var testRegistrationName = GetTestRegistrationName(name);

            container.RegisterType<T,U>(testRegistrationName);
        }

        private static string GetTestRegistrationName(string name)
        {
            var rawTypeName = new StackFrame(2).GetMethod().DeclaringType.FullName;
            string testRegistrationName = (rawTypeName.Contains("+") ? 
                                                CallingTypeRegex.Match(rawTypeName).Groups["TypeName"].Value
                                                : rawTypeName)
                + (!string.IsNullOrWhiteSpace(name) ? "_" + name : "");
            return testRegistrationName;
        }

        public static T ResolveTest<T>(this IUnityContainer container, string name = "")
        {
            return container.Resolve<T>(GetTestRegistrationName(name));
        }
    }
}
